#pragma once
// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: web_page.h
// Description: WebPage Class
//      Author: Ziming Li
//     Created: 2022-05-01
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#ifndef BLINKIT_WEB_PAGE_H
#define BLINKIT_WEB_PAGE_H

#include "blinkit/blink/public/web/WebInputEvent.h"
#include "blinkit/blink/renderer/core/loader/frame_loader_client.h"
#include "blinkit/blink/renderer/web/page_widget_delegate.h"

namespace blink {
struct PageClients;
class WebLayer;
class WebLayerTreeView;
}

namespace BlinKit {

class WebPageHost;

class WebPage : public FrameLoaderClient, public PageWidgetEventHandler
{
public:
    ~WebPage(void) override;

    WebPageHost* Host(void) { return m_host; }
    LocalFrame* GetFrame(void) const { return m_frame.get(); }
    Page* GetPage(void) const { return m_page.get(); }

    virtual WebInputEventResult ProcessInput(const WebInputEvent &e);

    const IntSize& Size(void) const { return m_size; }
    virtual void Resize(const IntSize &size) { m_size = size; }

    void ConvertViewportToWindow(IntRect *rect) const;

    void PerformAnimation(double tick);
    void ScheduleAnimation(void);

    void PageWillBeClosed(void) { /* Currently nothing to do. */ }
protected:
    WebPage(WebPageHost *host = nullptr);

    void Initialize(const PageClients &pageClients, float scaleFactor);

    void SetHost(WebPageHost *host)
    {
        ASSERT(nullptr != host);
        ASSERT(nullptr == m_host);
        m_host = host;
    }

    bool HasFrame(void) const { return !!m_frame; }

    bool HasPage(void) const { return !!m_page; }
    void DestroyPage(void);

    void ResumeTreeViewCommitsIfRenderingReady(void);
    virtual void UpdateLifecycle(void);

    WebLayerTreeView *m_layerTreeView = nullptr;
    WebLayer *m_rootLayer = nullptr;
    GraphicsLayer *m_rootGraphicsLayer = nullptr;
private:
    virtual void OnFrameCreated(LocalFrame *frame) {}

    // FrameClient
#ifdef BLINKIT_FULL_BUILD
    Type GetType(void) const override { return Type::UIWidget; }
#endif
    // FrameLoaderClient
    void dispatchDidFinishDocumentLoad(bool documentIsEmpty) final;

    WebPageHost *m_host;
    IntSize m_size;
    std::unique_ptr<Page> m_page;
    GCUniquePtr<LocalFrame> m_frame;
};

} // namespace BlinKit

#endif // BLINKIT_WEB_PAGE_H
